import request from '@/utils/request'
import type { ApiResponse } from '@/types'

export interface TradeItem {
  tradeId: string
  userId: string
  title: string
  description: string
  pic1?: string
  pic2?: string
  pic3?: string
  price: number
  createTimestamp: number
  updateTimestamp: number
  nickName?: string
}

export interface TradeQuery {
  pageNo: number
  pageSize: number
  sortBy?: string
  isAsc?: boolean
  endKey?: string
  startTimestamp?: number
  str?: string
}

export interface TradeDto {
  title: string
  description: string
  pic1?: string
  pic2?: string
  pic3?: string
  price: number
}

export interface TradeUpdateDto {
  tradeId: string
  title: string
  description: string
  pic1?: string
  pic2?: string
  pic3?: string
  price: number
}

export interface PageQuery {
  pageNo: number
  pageSize: number
  sortBy?: string
  isAsc?: boolean
  endKey?: string
  startTimestamp?: number
}

export const tradeApi = {
  // 主页展示商品 - POST /trade/queryMainTrade
  getList: (params: TradeQuery): Promise<ApiResponse<any>> => {
    console.log('发送二手交易请求:', params)
    return request({
      method: 'POST',
      url: '/trade/queryMainTrade',
      data: params
    })
  },

  // 获取单个商品详情 - GET /trade/query/{tradeId}
  getDetail: (tradeId: string): Promise<ApiResponse<TradeItem>> => {
    return request.get(`/trade/query/${tradeId}`)
  },

  // 添加商品 - POST /trade/add
  add: (data: TradeDto): Promise<ApiResponse<any>> => {
    return request({
      method: 'POST',
      url: '/trade/add',
      data: data
    })
  },

  // 修改商品 - POST /trade/updateTrade
  edit: (data: TradeUpdateDto): Promise<ApiResponse<any>> => {
    return request({
      method: 'POST',
      url: '/trade/updateTrade',
      data: data
    })
  },

  // 删除我的商品 - DELETE /trade/delete/{tradeId}
  delete: (tradeId: string): Promise<ApiResponse<any>> => {
    return request.delete(`/trade/delete/${tradeId}`)
  },

  // 分页查询我的商品 - POST /trade/queryMyTrade
  getMyTrade: (params: PageQuery): Promise<ApiResponse<any>> => {
    return request({
      method: 'POST',
      url: '/trade/queryMyTrade',
      data: params
    })
  }
}